// pages/address-edit/address-edit.js
import { addressApi } from '../../utils/api.js'
import { checkLoginAndRedirect } from '../../utils/auth.js'
import { ADDRESS_LABELS, GENDER } from '../../utils/constants.js'

const app = getApp()

Page({
  data: {
    loading: false,
    isEdit: false,
    addressId: null,
    formData: {
      consignee: '',
      phone: '',
      sex: GENDER.MALE,
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      districtCode: '',
      districtName: '',
      detail: '',
      label: '',
      isDefault: 0
    },
    addressLabels: ADDRESS_LABELS,
    showLabelPicker: false,
    showGenderPicker: false,
    genderOptions: [
      { value: GENDER.MALE, label: '先生' },
      { value: GENDER.FEMALE, label: '女士' }
    ]
  },

  onLoad(options) {
    const { id } = options
    
    if (id) {
      this.setData({
        isEdit: true,
        addressId: id
      })
      this.loadAddressDetail()
    } else {
      this.setData({
        isEdit: false
      })
    }
  },

  // 加载地址详情
  async loadAddressDetail() {
    if (!checkLoginAndRedirect()) return

    try {
      this.setData({ loading: true })
      
      const res = await addressApi.getById(this.data.addressId)
      
      if (res.code === 1) {
        this.setData({
          formData: res.data
        })
        
        // 设置导航栏标题
        wx.setNavigationBarTitle({
          title: '编辑地址'
        })
      }
    } catch (error) {
      console.error('加载地址详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 输入框变化
  onInputChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 选择地区
  chooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        // 这里需要根据实际的位置信息解析省市区
        // 暂时使用模拟数据
        this.setData({
          'formData.detail': res.address,
          'formData.provinceName': '北京市',
          'formData.cityName': '北京市',
          'formData.districtName': '朝阳区',
          'formData.provinceCode': '110000',
          'formData.cityCode': '110100',
          'formData.districtCode': '110105'
        })
      },
      fail: (error) => {
        console.error('选择位置失败:', error)
        wx.showToast({
          title: '选择位置失败',
          icon: 'none'
        })
      }
    })
  },

  // 显示标签选择器
  showLabelSelector() {
    this.setData({
      showLabelPicker: true
    })
  },

  // 选择标签
  selectLabel(e) {
    const label = e.currentTarget.dataset.label
    this.setData({
      'formData.label': label,
      showLabelPicker: false
    })
  },

  // 显示性别选择器
  showGenderSelector() {
    this.setData({
      showGenderPicker: true
    })
  },

  // 选择性别
  selectGender(e) {
    const { value, label } = e.currentTarget.dataset
    this.setData({
      'formData.sex': value,
      showGenderPicker: false
    })
  },

  // 切换默认地址
  toggleDefault() {
    this.setData({
      'formData.isDefault': this.data.formData.isDefault === 1 ? 0 : 1
    })
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data
    
    if (!formData.consignee.trim()) {
      wx.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.phone.trim()) {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      })
      return false
    }
    
    // 简单的手机号验证
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(formData.phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.detail.trim()) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return false
    }
    
    return true
  },

  // 保存地址
  async saveAddress() {
    if (!checkLoginAndRedirect()) return
    
    if (!this.validateForm()) return
    
    try {
      this.setData({ loading: true })
      
      const { isEdit, addressId, formData } = this.data
      let res
      
      if (isEdit) {
        // 编辑地址
        res = await addressApi.update({
          ...formData,
          id: addressId
        })
      } else {
        // 新增地址
        res = await addressApi.add(formData)
      }
      
      if (res.code === 1) {
        wx.showToast({
          title: isEdit ? '修改成功' : '添加成功',
          icon: 'success'
        })
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        throw new Error(res.msg || '保存失败')
      }
    } catch (error) {
      console.error('保存地址失败:', error)
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 取消选择器
  cancelPicker() {
    this.setData({
      showLabelPicker: false,
      showGenderPicker: false
    })
  }
})
